package com.viknix.threadpool.manager.cluster.executor;

import com.viknix.threadpool.manager.server.dependence.factory.ExecutorFactory;
import com.viknix.threadpool.manager.server.dependence.factory.NameThreadFactory;
import com.viknix.threadpool.manager.server.dependence.util.ClassUtils;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @Author: Dongqi
 * @Date: 2021/11/12 14:35
 * @Version 1.0
 * @Description: 全局执行器。
 */
@SuppressWarnings("all")
public class GlobalExecutor {

    /**
     * 负责执行当前节点与其余节点的通信任务
     */
    private static final ScheduledExecutorService COMMON_EXECUTOR = ExecutorFactory.Managed
            .newScheduledExecutorService(ClassUtils.getCanonicalName(GlobalExecutor.class), 4,
                    new NameThreadFactory("com.viknix.threadpool.manager.cluster.executor.common"));

    private static final ScheduledExecutorService DISTRO_EXECUTOR = ExecutorFactory.Managed
            .newScheduledExecutorService(ClassUtils.getCanonicalName(GlobalExecutor.class),
                    Runtime.getRuntime().availableProcessors() * 2,
                    new NameThreadFactory("com.viknix.threadpool.manager.cluster.executor.distro"));

    public static void runWithoutThread(Runnable runnable) {
        runnable.run();
    }

    public static void executeByCommon(Runnable runnable) {
        if (COMMON_EXECUTOR.isShutdown()) {
            return;
        }
        COMMON_EXECUTOR.execute(runnable);
    }

    public static void scheduleByCommon(Runnable runnable, long delayMs) {
        if (COMMON_EXECUTOR.isShutdown()) {
            return;
        }
        COMMON_EXECUTOR.schedule(runnable, delayMs, TimeUnit.MILLISECONDS);
    }

    public static void submitLoadDataTask(Runnable runnable) {
        DISTRO_EXECUTOR.submit(runnable);
    }

    public static void submitLoadDataTask(Runnable runnable, long delay) {
        DISTRO_EXECUTOR.schedule(runnable, delay, TimeUnit.MILLISECONDS);
    }

    public static void schedulePartitionDataTimedSync(Runnable runnable, long interval) {
        DISTRO_EXECUTOR.scheduleWithFixedDelay(runnable, interval, interval, TimeUnit.MILLISECONDS);
    }

}
